/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
        "fmt"
        "github.com/howeyc/fsnotify"
        "os"
        "regexp"
        "sync"
        "time"
)

const TEST_DIR = "/Datas/TestDir"

var (
        watchCloseChan = make(chan bool)
        dirModChan     = make(chan bool)
        dirWatchMap    = make(map[string]*fsnotify.Watcher)
        prevEventStr   = ""
        mutex          = new(sync.Mutex)
        preTimestamp   = int64(0)
        watcher        *fsnotify.Watcher
)

func watchDirs(dirs []string) {
        for _, dir := range dirs {
                watcher.Watch(dir)
                //fmt.Println("Watch Dir: ", dir)
        }

        for {
                select {
                case ev := <-watcher.Event:
                        if ev == nil {
                                break
                        }

                        if ok, _ := regexp.MatchString(`\.swa?px?$`,
                                ev.Name); ok {
                                break
                        }

                        fmt.Println("\nEvent: ", ev)
                        //fmt.Printf("Prev Event: %s\n",
                        //prevEventStr)
                        if ev.IsCreate() || ev.IsDelete() {
                                if prevEventStr == ev.String() {
                                        break
                                }

                                //if getCurrentTimestamp()-preTimestamp < 1 {
                                //break
                                //}

                                prevEventStr = ev.String()
                                fmt.Println("Emit Dir Modify")
                                preTimestamp = getCurrentTimestamp()
                                dirModChan <- true
                                return
                        }
                }
        }
}

func getAllDirName(dir string) []string {
        f, err := os.Open(dir)
        if err != nil {
                fmt.Printf("Open '%s' failed: %v\n", dir, err)
                return []string{}
        }
        defer f.Close()

        finfos, err1 := f.Readdir(0)
        if err1 != nil {
                fmt.Printf("Readdir '%s' failed: %v\n", dir, err1)
                return []string{}
        }

        dirs := []string{}
        dirs = append(dirs, dir)
        for _, info := range finfos {
                if info == nil || !info.IsDir() {
                        continue
                }

                tmp := getAllDirName(dir + "/" + info.Name())
                dirs = append(dirs, tmp...)
        }

        return dirs
}

func resetWatchDir(dir string) {
        for {
                select {
                case <-dirModChan:
                        mutex.Lock()
                        dirs := getAllDirName(dir)
                        go watchDirs(dirs)
                        mutex.Unlock()
                }
        }
}

func getCurrentTimestamp() int64 {
        t := time.Now().Unix()
        fmt.Println("Timestamp:", t)
        return t
}

func main() {
        var err error
        watcher, err = fsnotify.NewWatcher()
        if err != nil {
                fmt.Printf("New Watch Failed Error: %v\n", err)
                return
        }
        defer watcher.Close()

        dirs := getAllDirName(TEST_DIR)
        go watchDirs(dirs)
        go resetWatchDir(TEST_DIR)

        select {}
}
